﻿using System;
using System.Globalization;
using System.Linq;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using PS.Practices.Provisioner.Provisioner.Util;
using PS.Practices.SiteBuilder.Features.Schema;
using PS.Practices.Provisioner.Util;

namespace PS.Practices.Provisioner.Activation
{
    /// <summary>
    /// Web Events
    /// </summary>
    public class EventSink : SPWebEventReceiver
    {
       /// <summary>
       /// A site was provisioned.
       /// </summary>
       public override void WebProvisioned(SPWebEventProperties properties)
       {
           SPWeb spWeb = properties.Web;
           var i = new Interpreter();
           SPListItem locatedProvisionerItem = LocateProvisionerItem(spWeb);//LocateScript(spWeb);

           var cTYpe = ListUtil.TryGetListItemProperty(locatedProvisionerItem, "ContentType0");

           //Only run this if it hasn't been run already by the UI event handler
           if (string.IsNullOrEmpty(cTYpe.ToString()))
           {
               i.ProcessScript(spWeb, locatedProvisionerItem["Script"].ToString());
           }
       }

       internal static SPListItem LocateProvisionerItem(SPWeb web)
       {
           //var associatedTemplate = String.Format("{0}#{1}", web.WebTemplate, web.WebTemplateId);

           // It looks like in 2010 we have to use the configuration property of the web
           var associatedTemplate = String.Format("{0}#{1}", web.WebTemplate, web.Configuration);

           var fd = web.Features.ToDictionary(d => d.DefinitionId, d => d.Definition.GetTitle(CultureInfo.InvariantCulture));

           foreach (var feature in web.Features)
           {
               if (feature.Definition.GetTitle(CultureInfo.InvariantCulture).Contains("PropertyBag feature of exported web template"))
               {
                   var id = feature.Definition.SolutionId;
                   var sol = web.Site.Solutions[id];
                   associatedTemplate = sol.Name;
                   break;
               }
           }

           var rootWeb = web.Site.RootWeb;
           var provScriptList = rootWeb.Lists["Provisioner Scripts"];

           var query = new SPQuery
                           {

                               Query =
                                   String.Format(
                                   "<Where><Eq><FieldRef Name='Templates'/><Value Type='Text'>{0}</Value></Eq></Where>",
                                   associatedTemplate),
                               RowLimit = Constants.SpQueryRowLimit
                           };

           SPListItemCollection myItems = provScriptList.GetItems(query);

           if (myItems.Count > 0)
           {
               return myItems[0];
           }

           return null;
       }
    }
}
